/**
 * ...
 * @author Franco Ponticelli
 */

package js;

class DomCreator {
	public static var creators(default, null) : Hash<Dynamic> ;
	
	static var _ = init();
	static function init() {
		creators = new Hash();
		var c = HDom.create;
		if (UA.isGecko || UA.isIe) {
			creators.set("option", function(html, _) {
				return c('<select>' + html + '</select>');
			});
			creators.set("tr", function(html, _) {
				return c('<tbody>' + html + '</tbody>');
			});
			creators.set("td", function(html, _) {
				return c('<tr>' + html + '</tr>');
			});
			creators.set("tbody", function(html, _) {
				return c('<table>' + html + '</table>');
			});
			creators.set("legend", "fieldset");
			creators.set("col", creators.get("tbody"));
		}
		if (UA.isIe) {
			// TODO: thead/tfoot with nested tbody
			// IE adds TBODY when creating TABLE elements (which may share this impl)
			creators.set("tbody", function(html, _) {
				var frag = c('<table>' + html + '</table>');
				var tb = untyped frag.children.tags('tbody')[0];
				var re_tbody = ~/(?:\/(?:thead|tfoot|tbody|caption|col|colgroup)>)+\s*<tbody/;
				if (untyped frag.children.length > 1 && tb && re_tbody.match(html)) {
					untyped tb['parentNode'].removeChild(tb); // strip extraneous tbody
				}
				return frag;
			});
			creators.set("script", function(html, doc, _) {
				var frag = doc.createElement('div');
				frag.innerHTML = '-' + html;
                frag.removeChild(untyped frag['firstChild']);
                return frag;
			});
		}
		
		if (UA.isGecko || UA.isIe) {
			creators.set("th", creators.get("td"));
			creators.set("thead", creators.get("tbody"));
			creators.set("tfoot", creators.get("tbody"));
			creators.set("caption", creators.get("tbody"));
			creators.set("colgroup", creators.get("tbody"));
			creators.set("col", creators.get("tbody"));
			creators.set("optgroup", creators.get("option"));
		}
	}
}